package com.example.imchat.controller.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.example.imchat.R;
import com.example.imchat.controller.adapter.GroupDetailAdapter;
import com.example.imchat.model.Model;
import com.example.imchat.model.bean.UserInfo;
import com.example.imchat.utils.Constant;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.exceptions.HyphenateException;
import java.util.ArrayList;
import java.util.List;

/*
* 20/5/24 lee
* */
public class GroupDetailActivity extends Activity {
    private GridView gv_groupdetail;
    private Button bt_groupdetail_out;
    private EMGroup mGroup;
    private GroupDetailAdapter groupDetailAdapter;
    private  List<UserInfo> mUsers;
    private GroupDetailAdapter.OnGroupDetailListener mOnGroupDetailListener = new GroupDetailAdapter.OnGroupDetailListener() {
        @Override
        public void onAddMembers() {
            //添加群成员
            //跳转到选择联系人界面
            Intent intent = new Intent(GroupDetailActivity.this, PickContactActivity.class);
            //传递一个群id   去选择联系人界面选择当前群成员
            intent.putExtra(Constant.GROUP_ID,mGroup.getGroupId());

            startActivityForResult(intent,2);

        }

        @Override
        public void onDeleteMembers(UserInfo user) {
            //删除群成员
            Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        //从换新服务器中删除群成员
                        EMClient.getInstance().groupManager().removeUserFromGroup(mGroup.getGroupId(),user.getName());

                        //更新页面
                        getMembersFromHxServer();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(GroupDetailActivity.this,"删除 "+user.getName()+" 成功",Toast.LENGTH_SHORT).show();
                            }
                        });
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(GroupDetailActivity.this,"删除 "+user.getName()+" 失败"+e,Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                }
            });

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode  == RESULT_OK){
            String[] members = data.getStringArrayExtra("members");
            Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        //去环信服务器发送邀请
                        EMClient.getInstance().groupManager().addUsersToGroup(mGroup.getGroupId(),members);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(GroupDetailActivity.this,"发送邀请成功",Toast.LENGTH_SHORT).show();
                            }
                        });

                    } catch (HyphenateException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(GroupDetailActivity.this,"发送邀请失败"+e,Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            });

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_detail);

        initVIew();
        getData();
        initData();
        initListener();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {
        gv_groupdetail.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {//判断当前是否是删除模式  ，如果是删除模式
                    if (groupDetailAdapter.ismIsDeleteModify()) {
                        //切换为非删除模式
                        groupDetailAdapter.setmIsCanModify(false);
                        //刷新页面
                        groupDetailAdapter.notifyDataSetChanged();
                    }
                }
                return false;
            }
        });
    }

    private void initData() {
        //初始化button显示
        initButtonDisplay();

        //初始化gridview
        initGridView();
        //从环信获取所有群成员
        getMembersFromHxServer();
    }

    private void getMembersFromHxServer() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    //从环信获取所有群成员
                    EMGroup emGroup = EMClient.getInstance().groupManager().getGroupFromServer(mGroup.getGroupId());
                    List<String> members = emGroup.getMembers();
                    if (members != null && members.size()>=0){
                        mUsers = new ArrayList<>();
                        //转换
                        for (String member:members){
                            UserInfo userInfo = new UserInfo(member);
                            mUsers.add(userInfo);
                        }
                    }

                    //更新页面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //刷新适配器
                            groupDetailAdapter.refresh(mUsers);
                        }
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(GroupDetailActivity.this,"加载群信息失败"+e,Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    private void initGridView() {
        //初始化gridview
        //当前用户是群主或者有开放权限
        boolean isCanModify =  EMClient.getInstance().getCurrentUser().equals(mGroup.getOwner()) || mGroup.isPublic();

        groupDetailAdapter = new GroupDetailAdapter(this,isCanModify,mOnGroupDetailListener);
        gv_groupdetail.setAdapter(groupDetailAdapter);

    }

    private void initButtonDisplay() {
        //判断当前用户是否是群主
        if (EMClient.getInstance().getCurrentUser().equals(mGroup.getOwner())){

            bt_groupdetail_out.setText("解散该群");
            bt_groupdetail_out.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //去环信服务器解散该群
                                EMClient.getInstance().groupManager().destroyGroup(mGroup.getGroupId());
                                finish();
                                //发送群解散广播
                                exitGroupBroadCast();

                                //更新页面
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(GroupDetailActivity.this,"解散群成功",Toast.LENGTH_SHORT).show();

                                    }
                                });
                            } catch (HyphenateException e) {
                                e.printStackTrace();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(GroupDetailActivity.this,"解散群失败"+e,Toast.LENGTH_SHORT).show();
                                    }
                                });

                            }
                        }
                    });
                }
            });
        }else {
            bt_groupdetail_out.setText("退出该群");
            bt_groupdetail_out.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //通知环信服务器退出该群
                                EMClient.getInstance().groupManager().leaveGroup(mGroup.getGroupId());
                                exitGroupBroadCast();
                                finish();
                                //更新页面
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(GroupDetailActivity.this,"退群成功",Toast.LENGTH_SHORT).show();
                                    }
                                });
                            } catch (HyphenateException e) {
                                e.printStackTrace();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(GroupDetailActivity.this,"退群失败"+e,Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                        }
                    });
                }
            });
        }
    }

    private void exitGroupBroadCast() {
        //群解散和退群广播

        LocalBroadcastManager mLBM = LocalBroadcastManager.getInstance(GroupDetailActivity.this);

        Intent intent = new Intent(Constant.EXIT_GROUP);

        intent.putExtra(Constant.GROUP_ID,mGroup.getGroupId());

        mLBM.sendBroadcast(intent);


    }

    //获取传递过来的数据
    private void getData() {
        Intent intent = getIntent();
        String groupId = intent.getStringExtra(Constant.GROUP_ID);
        if (null == groupId){
            return;
        }else {
             mGroup = EMClient.getInstance().groupManager().getGroup(groupId);
        }
    }

    private void initVIew() {
        gv_groupdetail = findViewById(R.id.gv_groupdetail);
        bt_groupdetail_out = findViewById(R.id.bt_groupdetail_out);
    }
}
